package com.fenghongzhang.day014;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button start;
    private Button stop;
    private Intent intent;
    private Button bind;
    private Button unBind;
    private ServiceConnection connection;
    private MyService.MyBinder binder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        start = (Button) findViewById(R.id.start);
        stop = (Button) findViewById(R.id.stop);


        bind = (Button) findViewById(R.id.bind);
        unBind = (Button) findViewById(R.id.unBind);



        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开启服务
                intent = new Intent(MainActivity.this, MyService.class);
                startService(intent);

            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(intent);
            }
        });


        //绑定的方法启动一个服务.
        bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                Intent intent1 = new Intent(MainActivity.this, MyService.class);

                connection = new ServiceConnection() {
                    //建立链接调用
                    @Override
                    public void onServiceConnected(ComponentName name, IBinder service) {
                        binder = (MyService.MyBinder) service;
//                        binder.callShow();
                    }

                    //断开链接调用
                    @Override
                    public void onServiceDisconnected(ComponentName name) {

                    }
                };

                bindService(intent1,connection,BIND_AUTO_CREATE);

            }
        });


        unBind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unbindService(connection);
            }
        });
    }

    public void show2(View view) {
        binder.callShow2();
    }
}
